<?php

namespace app\controllers;

use app\award\Award;
use app\award\Profit;
use app\models\MonthProfit;
use app\models\order\Order;
use app\models\Queue;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\UserDown;
use app\services\Chain;

class QueueController extends Controller
{
    // public function actionIndex()
    // {
    //     $list = Queue::find()
    //         ->where(['status' => 0])
    //         ->orderBy(['id' => SORT_ASC])
    //         ->limit(30)
    //         ->all();
    //
    //     if (empty($list)) {
    //         echo '已经全部完成';
    //     }
    //
    //     foreach ($list as $item) {
    //         // 处理奖项
    //         $order = Order::findOne(['id' => $item->order_id]);
    //         if ($order) {
    //             $c = new Award($order);
    //             $c->exeProfit();
    //         }
    //
    //         $item->status = 1;
    //         $item->save();
    //     }
    // }

    // 用户降级
    // 30 2 1 * * /usr/bin/curl http://nl-api.97app.cn/queue/down
    public function actionDown()
    {
        set_time_limit(60 * 60 * 24);

        // 只降创2, 创3
        $users = User::find()
            ->where(['>', 'level', UserLevel::$keys['vip2']])
            ->all();

        $time = time();

        foreach ($users as $user) {
            $count = User::find()
                ->where(['referrer_id' => $user->id])
                ->andWhere(['>=', 'level', UserLevel::$keys['vip1']])
                ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
                ->count();

            if ($count < 2) {
                $t = strtotime($user->create_time);
                $t = $time - $t;
                $t = $t / 24 / 3600;

                if ($t < 30) {
                    continue;
                }

                echo "\n", $user->id, ' ', $user->create_time, ' ', $t;

                // 降级
                if ($t >= 30) {
                    $down = new UserDown();
                    $down->user_id = $user->id;
                    $down->old_level = $user->level;
                    $down->new_level = $user->level - 1;
                    $down->save();

                    $user->level -= 1;
                    $user->save();
                }
            }
        }

        echo "\n", '全部完成..........';

        // var_dump($users);
    }

    /*
     * 0 1 1 * * command           #每月1号凌晨1点执行一次
     *
     * 每月1号2:30执行
     * 30 2 1 * * /usr/bin/curl http://nl-api.97app.cn/queue/index
     */
    public function actionIndex()
    {
        // 测试现有的, 非上个月
        $test = $this->get('test', 0);
        $test = $test > 0;

        set_time_limit(60 * 60 * 24);

        $type = 30;
        $name = '分红';

        $has = MonthProfit::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
            ->one();
        if ($has) {
            return '已分过红了...';
        }

        $list = Profit::getList($test);
        // var_dump($list);exit;

        foreach ($list as $item) {
            if ($item == 0) {
                continue;
            }

            // 每月必须直推2单
            $ids = User::find()
                ->where(['referrer_id' => $item])
                ->select(['id'])
                ->column();
            // var_dump($ids);exit;
            $query = Order::find()
                ->where(['user_id' => $ids])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']]);

            if (!$test) {
                // 上个月必须推两单
                $query->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')");
            }

            $count = $query->count();
            if (intval($count) < 2) {
                continue;
            }

            $this->saveCommission($item, $type, $name);
            echo '佣金: ', $item['id'], ' , 金额: ', $item['result_amount'], "\n";
        }

        echo '处理完毕.........';

    }

    // 保存佣金
    protected function saveCommission($item, $type, $name, $status = 1)
    {
        $balance = $item['result_amount'];
        $user_id = $item['id'];

        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = 0;
            $model->order_id = 0;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                    $account->save();
                } else {
                    $account->await_balance += $balance;
                    $account->save();
                }
            }

            // 记录数量
            $log = new MonthProfit();
            $log->user_id = $user_id;
            $log->amount = $item['amount'];
            $log->real_quantity = $item['real_quantity'];
            $log->result_amount = $item['result_amount'];
            $log->quantity = $item['quantity'];
            $log->save();
        }
    }
}